package com.zoo.diannaopeijian.common.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.Map.Entry;

/**
 * Created by zx583 on 2018-01-19.
 */
public class TreeUtil {
    public static List<Map> buildEasyUITree(List<Map> sources, List<String> nodeName) {
        if (sources == null || nodeName == null) {
            throw  new NullPointerException("params can not be null");
        }

        return buildTreeNodes(sources, nodeName, "", 0);
    }

    private static List<Map> buildTreeNodes(List<Map> sources, List<String> nodeName, String id, int layer) {
        List<Map> result = new ArrayList<>();

        Integer num = 1;

        // 遍历source构造node
        for (Map source : sources) {
            result.add(buildTreeNode(source, nodeName, id + num.toString(), layer));
            num++;
        }

        // 返回结果
        return result;
    }

    private static Map buildTreeNode(Map<String, Object> source, List<String> nodeName, String id, int layer) {
        Map result = new HashMap();

        result.put("id", id);

        if (layer >= nodeName.size()) throw new RuntimeException("nodeName is not deep enough");
        String textName = nodeName.get(layer);

        for (Entry entry : source.entrySet()) {
            if (entry.getKey().equals(textName)) {
                result.put("text", source.get(textName));
                continue;
            }

            if (entry.getValue() instanceof  List) {
                result.put("children", buildTreeNodes((List) entry.getValue(), nodeName, id, layer + 1));
                continue;
            }

            result.put(entry.getKey(), entry.getValue());
        }


        return result;
    }

}
